<script setup>
import {onMounted, ref} from "vue";
import { Search } from '@element-plus/icons-vue'
import { ArrowDown } from '@element-plus/icons-vue'
import {gsap} from "gsap";
import router from "@/router/index.js";
import axios from "axios";
import {HTTP} from "@/api/HTTP.js"
import {ElMessage, ElMessageBox} from "element-plus";
import useTokenStore from "@/stores/User/token.js";

const Token = useTokenStore()
//时间下拉列表组件开发
let selected = ref(1)
let selectedState = ref("近一年")
const change = (text) =>{
  selected.value = text;
  console.log(selected.value)
  selectedState = selectStates.value.find(item => item.id === selected.value)?.text
  console.log(selectedState.value)
  fetchData();
}

//根据状态查询，切换查询的订单状态
let currentState = ref(1);
const changeState = (num) => {
  states.value.forEach((state) => {
    state.state = (state.id === num);
  });
  currentState.value = num;
  fetchData();
};

//默认状态
let selectStates = ref([
  { id: 1, text: '近一年' ,state:false},
  { id: 2, text: '近半年' ,state:false},
  { id: 3, text: '近三个月' ,state:false}
])
let states = ref([
  { id: 0, text: '全部订单',state:true},
  { id: 1, text: '待付款' ,state:false},
  { id: 2, text: '待收货' ,state:false},
  { id: 3, text: '待评价' ,state:false}
])


//输入框
let input = ref('');

//页面加载完毕猫猫从空中落下
onMounted(() => {
  gsap.from('.cat',{duration: 2,y: -300,rotate:-720,ease:'bounce.out'})
})

//控制猫猫移动动画
const catMove = () =>{
  let timeline = gsap.timeline()
  timeline.to('.cat',{duration: 2,y: -250,ease:'bounce.in'})
  timeline.to('.cat',{duration: 2,y: 0,ease:'bounce.out'})
}

//返回上一级页面
const back = () =>{
  router.push("/home")
}

let form = ref({
  data: []
})

//axios 配置
let data = new FormData();
data.append('state', currentState.value);
data.append('time', selected.value);
data.append('name', input.value);

async function fetchData() {
  form.value =  {
    data: []
  }
  try {
    await axios({
      method: 'post',
      baseURL:'http://localhost:8080',
      url: '/order',
      data: data,
      //   {
      // 'state': currentState.value,
      // 'time': selectStates.value.find(item => item.text === selected.value)?.id,
      // 'name': input.value
      //   },
      headers: {
        'token': Token.loginToken
      }
    })
        .then(res => {
          if (res.data.code === 10205){
            ElMessage({
              type: 'error',
              message: '请先登录',
            })
            router.push("/login")
          }else if (res.data.code === 10200){
            console.log(res)
            res.data.data.orderVoList.forEach((item) => {
              form.value.data.push(item);
            })
          }
        })
        .catch(err => {
          console.log(Token.loginToken);
          console.log(err)
          console.log(data)
        })

  } catch (error) {
    // 打印错误信息
    console.error('Error fetching data:', error);
  }
}

onMounted(() =>{
      // 调用函数
      fetchData();
    }
)

//动画锁+详情页弹窗
let canTrigger = true; // 控制动画触发的标志
let dialogVisible = ref(false);
let currentItem = null;
const show = (event,item) => {
  if (!canTrigger) return; // 如果不能触发，直接返回
  let time = gsap.timeline()
  time.to(event.target, { rotate: 180, duration: 1, yoyo: true, repeat: 1, onComplete: () => {
      canTrigger = true; // 动画完成后，允许下一次触发
    }});
  canTrigger = false;
  setTimeout(() => {
    dialogVisible.value = true;
  },1000)
  currentItem = item;
}

const deleteOrder = (id) => {
  ElMessageBox.confirm(
      '确认删除订单信息嘛?',
      {
        confirmButtonText: '确定！',
        cancelButtonText: '算了',
        type: 'warning',
      }
  )
      .then((res) => {
        console.log(res)
        HTTP.delete('/order', {
          method:'delete',
          params:{
            orderId: id
          }
        })
            .then(res => {
              console.log(res);
              // 重新获取数据
              fetchData();
              ElMessage({
                type: 'success',
                message: '成功删除',
              })
            })
            .catch(err => {
              console.log(err);
            })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
</script>

<template>
  <div class="flex">
    <div>
      <el-link class="iconfont icon-fanhui4 text-5xl" :underline=false @click="back"></el-link>
      <div class="state flex ml-40 mt-10">
        <div v-for="item in states" :key="item.id">
          <el-link :underline="false" class=" m-6 hover:font-black hover:text-red-400 " :class=" {select: item.state}" @click="changeState(item.id) ">{{ item.text }}</el-link>
        </div>
      </div>
      <div class="time search flex space-x-20">
        <div class="flex items-center w-20 ml-40">
          <el-dropdown>
            <span class="el-dropdown-link">
              {{ selectedState }}
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="change(1)">近一年</el-dropdown-item>
                <el-dropdown-item @click="change(2)">近半年</el-dropdown-item>
                <el-dropdown-item @click="change(3)">近三个月</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div>
          <el-input
              v-model="input"
              style="width: 240px"
              placeholder="搜索订单"
              :suffix-icon="Search"
          />
        </div>
      </div>
      <div class="content">
        <div v-for="item in form.data" :key="item.id" class="ml-28">
          <div class="flex space-x-10 m-6">
            <div class="w-32 h-40 flex items-center justify-center overflow-hidden shadow-2xl">
              <img :src="item.img" alt="pic" class="w-full h-full img" @click="show($event,item)" >
            </div>
            <div class="flex flex-column justify-between">
              <div>
                <div>{{item.productName}}</div>
                <div v-for="config in item.type" :key="item.orderId">
                  {{ config }}
                </div>
              </div>
              <div>
                <div>{{ item.date }}</div>
                <div class="inline">订单号: {{ item.orderId }}</div>
              </div>
            </div>
            <div class="flex flex-column justify-between pl-52">
              <el-link class="iconfont icon-quxiao text-end" @click="deleteOrder(item.orderId)" :underline="false"></el-link>
              <div>{{ item.state}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="icon flex flex-col items-center justify-center mt-16">
      <img src="@/assets/icon/cat.png" alt="喵喵喵" class="cat" @click="catMove">
      <div>喵喵订单~</div>
    </div>

    <el-dialog v-model="dialogVisible" title="订单详情" width="800" draggable>
      <div>订单名：{{currentItem.productName}}</div>
      <div>订单配置：</div>
      <div v-for="config in currentItem.type" :key="currentItem.id">
        {{ config }}
      </div>
      <div>价格：{{currentItem.amount}}</div>
      <div>收货地址：{{currentItem.address}}</div>
      <div>收货人：{{currentItem.consignee}}</div>
      <div>下单时间：{{currentItem.date}}</div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
  .select{
    color: #ff7070;
  }
  //去除选择元素出现的黑边框
  .el-dropdown-link:focus {
    outline: none;
  }

  .iconfont{
    font-size: 48px;
  }
</style>